var utils = require('../../utils/util.js');
var http = utils.http;
var modal = utils.modal;

console.log(utils.http);
Page({
  data: {
    commenAvatar: "//gss0.bdstatic.com/6LZ1dD3d1sgCo2Kml5_Y_D3/sys/portrait/item/11b5c6f5b7f2c6ebc0efb0c2375dab?t=1536198212727",
    topPosition: {
      top: 0,
      zIndex: 1,
      changePosition: 'absolute'
    },

    maskdisplay: false,
    showLogin: false,
    animationData: {},
    _num: 0,
    nameFoucs: false,
    pwdFoucs: false,
    showState: false,
    status: 0,
    //服务器传回数据
    postList: {
      list: [],
      page: 1,
      cur: 1,

    },
    name: "",
    post_num: "",
    slogn: "",
    logo: "",
    sid: "",
    // 置顶帖
    top: [],
    inpValue: '',
    pwdValue: '',
    isLogin: false
  },

  // 页面首次加载就去获取数据
  onLoad: function() {

    var that = this;
    console.log("有哪些用户", getApp().globalData.userobj);
    if (getApp().globalData.userobj) {
      var collections = wx.getStorageSync(getApp().globalData.userobj.id + 's');
      console.log("我的点赞数组为", collections);
    }

    that.getPostList(that.data.postList.cur);
    var query = wx.createSelectorQuery();
    query.select("#headtop").boundingClientRect();
    query.exec(function(res) {
      var str = "topPosition.top"
      that.setData({
        [str]: res[0].height,
      });
    });
  },

  onShow: function() {

  },
  // 从服务器端获取返回的帖子列表首页数据
  getPostList: function(p) {
    var that = this;
    http.get("/", {
      p: p
    }, function(resp) {
      console.log(resp);
      if (resp.data.index.postList.list.length > 0) {
        parseInt(resp.data.index.postList.cur) > 1 ? resp.data.index.postList.list = that.data.postList.list.concat(resp.data.index.postList.list) : that.data.postList.list = resp.data.index.postList.list;

        console.log("当前要显示的数据", resp.data.index.postList.list);
        var list = 'postList.list';
        var total = "postList.page";

        that.setData({
          [list]: resp.data.index.postList.list,
          [total]: resp.data.index.postList.page,
          // 贴吧名称
          name: resp.data.index.name,
          logo: resp.data.index.logo,
          slogn: resp.data.index.slogn,
          top: resp.data.top,
          post_num: resp.data.index.post_num,
          sid: resp.data.sid
        });
      }

    });

  },

  // 滚动到底部，发送请求，即向服务器要求下一页的数据。
  onReachBottom: function(e) {
    var that = this;
    if (parseInt(that.data.postList.cur) >= that.data.postList.page)
      return;
    var curpage = "postList.cur";
    that.setData({
      [curpage]: parseInt(that.data.postList.cur) + 1
    });
    that.getPostList(that.data.postList.cur);
  },

  // 底部蒙版
  showModal: function() {
    if (getApp().globalData.userobj) {
      var collections = wx.getStorageSync(getApp().globalData.userobj.id + 's');
      console.log("我的点赞数组为", collections);
    }
    var _this = this;
    _this.setData({
      maskdisplay: true
    });
    modal.show({
      duration: 200,
      timingFunction: "ease"
    }, 0, _this);

  },

  // 取消蒙版显示
  cancelModal: function() {
    var _this = this;
    modal.hide({
      duration: 100,
      timingFunction: "ease"
    }, -167, _this);
    setTimeout(function() {
      _this.setData({
        maskdisplay: false
      });
    }, 200)

  },

  // 切换导航条
  onTabChange: function(event) {
    this.setData({
      _num: event.currentTarget.dataset.num
    });
  },

  // 头部定位更改
  onPageScroll: function(e) {
    var scrollHead = utils.scrollHead;
    var _this = this;
    scrollHead(e, _this);
  },

  // 点击页面上某个帖子，跳转进入到详情页面。
  // skipToDetail: function(e) {
  //   var userid = e.currentTarget.id;
  //   console.log("当前是谁点击了我", userid);
  //   wx.navigateTo({
  //     url: '../post/detail/detail?id=' + userid + "&name=" + this.data.name
  //   });
  // },


  addOrlogin: function() {
    // 未登录就跳转到登录注册界面
    console.log("获取的登录对象", getApp().globalData.userobj);
    if (!getApp().globalData.userobj) {
      //  弹出登录注册界面
      this.setData({
        showLogin: true
      });
    }
    // 登录就跳转到发帖界面
    else {
      wx.redirectTo({
        url: '../post/add/add',
      })
    }

  },
  nameFocus: function() {
    this.setData({
      nameFoucs: true,
    });

  },

  pwdFocus: function() {
    this.setData({
      pwdFoucs: true
    });
  },
  inpBlur: function() {
    this.setData({
      pwdFoucs: false,
      nameFoucs: false
    });
  },

  // 关闭登录
  closeLogin: function() {
    this.setData({
      showLogin: false
    });
  },

  checkLogin: function(e) {
    var url = '/user/login';
    var _this = this;

    if (!e.detail.value.name && !e.detail.value.password) {
      wx.showToast({
        title: '请正确填写用户名和密码',
      })
      return;
    }
    _this.setData({
      isLogin: true
    });
    http.post(url, {
      name: e.detail.value.name,
      password: e.detail.value.password
    }, function(resp) {
      console.log("传递富哦来11111", resp);
      if (resp.data.info == "登录成功") {
        wx.showToast({
          title: resp.data.info
        })

        _this.closeLogin();
        // 将登陆后的用户对象存入全局变量
        getApp().globalData.userobj = resp.data.user
      } else {
        wx.showToast({
          title: '用户名或者密码错误',
          icon: "none"
        })
      }
    });
  },
  clearText: function(e) {
    if (e.currentTarget.dataset.info == "name")
      this.setData({
        inpValue: ''
      });
    else {
      this.setData({
        pwdValue: ''
      });
    }
  },
  // 点击点赞
  clickToLike: function(e) {
    var _this = this;
    var id = e.currentTarget.dataset.id;
    console.log("点zan点击了那个帖子", e, e.currentTarget.dataset.id);
    var isLike = 0;
    if (!getApp().globalData.userobj) {
      wx.showToast({
        title: '请先登陆后，再进行点赞操作',
        icon: 'none'
      })
    } else {
      var likeArr = [];
  
      _this.getAllSupport(function(res) {

        var mySupport = res.data.supportList.list;
        for (var i in mySupport) {
          likeArr.push(mySupport[i].post.id);
        }
        console.log("登陆后个人点赞数组", likeArr);
        var index = likeArr.indexOf(id);
        if (index != -1) {
          console.log("点赞过了");
          isLike = 0;
          likeArr.splice(index, 1);

          var key = 'postList';
          var item = _this.data.postList.list[id - 1];
          --item.supportCount;
          _this.setData({
            postList: _this.data.postList,
          });
          console.log("取消点赞");

        } else {
          isLike = 1;
          likeArr.push(id);
          var item = _this.data.postList.list[id - 1];
          ++item.supportCount;
          // 修改值 只能修改第一层
          _this.setData({
            postList: _this.data.postList,
            status: 1
          });
          console.log("添加收藏");
        }
        wx.setStorageSync(getApp().globalData.userobj.id + 's', likeArr);
        console.log("获取到的我的点赞数组", wx.getStorageSync(getApp().globalData.userobj.id + 's'), isLike);
        console.log("当前帖子点赞数为", _this.data.postList.list[id - 1].supportCount);
        var url = '/post/support';
        http.post(url, {
          id: parseInt(id),
          status: isLike
        }, function(resp) {
          console.log("点赞回帖", resp);
        });

      });


    }

  },
  preventHide: function() {

  },
  onShareAppMessage: function() {


  },

  getAllSupport: function(callback) {
    var url = "/user/support";
    var _this = this;
    http.get(url, {}, function(resp) {
      console.log("从服务器传来的点赞帖子为1111：", resp);
      callback(resp);
    });

  },

});